from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,BooleanField,SubmitField
from wtforms.validators import InputRequired,Length,Regexp,EqualTo
from wtforms import ValidationError
from app.models import User

class LoginForm(FlaskForm):
    name=StringField('用户名',validators=[InputRequired(),Length(1,7)])
    password=PasswordField('密码',validators=[InputRequired()])
    remember_me=BooleanField('记住我')
    submit=SubmitField('登录')

class RegistrationForm(FlaskForm):
    name=StringField('用户名',validators=[InputRequired(),Length(1,7),Regexp('^[A-Za-z][A-Za-z0-9_.]*$',0,'用户名要以字母开头，只能包含字母、数字、.和_')])
    password=PasswordField('密码',validators=[InputRequired(),EqualTo('password2',message='密码必须相同')])
    password2=PasswordField('确认密码',validators=[InputRequired()])
    note_name=StringField('备注',validators=[Length(0,10)])
    submit=SubmitField('注册')

    def validate_name(self,field):
        if User.query.filter_by(name=field.data).first():
            raise ValidationError('用户名已被使用')
        
class ChangePasswordForm(FlaskForm):
    old_password=PasswordField('旧密码',validators=[InputRequired()])
    password=PasswordField('新密码',validators=[InputRequired(),EqualTo('password2',message='密码必须相同')])
    password2=PasswordField('确认新密码',validators=[InputRequired()])
    submit=SubmitField('更新密码')